<script setup>
import { NCard,NInput,NImage,NFlex,NGradientText,NIcon,NButton,NSwitch,NDialogProvider,NForm,NFormItem} from 'naive-ui';
import logo from '../assets/logo.png'
import background from '../assets/background.png'
import {User,Lock} from '@vicons/tabler'
import {ref} from 'vue'
import UserRegCode from '@/components/UserRegCode.vue';
import UserRegister from '@/components/UserRegister.vue';
import UserUpdate from '@/components/UserUpdate.vue';
import axiosInstance from '@/utils/axios';
import { useLoginStore } from '@/stores/userlogin';
import { usemsgStore } from '@/stores/msgwrapper';
import { usedialogStore } from '@/stores/dialogwrapper';
import { useRouter } from 'vue-router';

// 存储用户的状态数据
const loginStore = useLoginStore()
// 封装消息的状态数据
const msgStore = usemsgStore()
// 封装对话框的状态数据
const dialogStore = usedialogStore()

const {sendMessage} = msgStore
const router = useRouter()
const formRef = ref(null)

const handleValidateClick = async (e) => {
  e.preventDefault();
  loginStore.loginButtonDisabled = true;
  try {
    await formRef.value?.validate();
    // 表单验证通过，执行登录请求
    const username = loginStore.formValue.username;
    const password = loginStore.formValue.password;
    sendMessage("loading",'正在检验登录进程', {
      duration: 1000,
      onAfterLeave: async () => {
        try {
          const res = await axiosInstance.post('/api/login', { username, password });
          // 选择持久存储还是会话存储
          const storage = loginStore.remember ? localStorage : sessionStorage;
          if (res.data.success && res.data.code === 200) {
            storage.setItem('token', res.data.token);
            sendMessage("success","登录成功", {
              duration: 500,
              onAfterLeave: () => {
                router.push('/home');
              }
            });
          } else {
            sendMessage("error","登录错误,请检查账号和密码或者账户被禁用");
          }
        } catch (error) {
          sendMessage("error","登录请求失败，请稍后再试.");
        } finally {
          loginStore.formValue.password = "";
          loginStore.loginButtonDisabled = false;
        }
      }
    });
  } catch (errors) {
    // 处理表单验证错误
    sendMessage("error","请完整填写信息")
    loginStore.loginButtonDisabled = false;
  }
};


</script>

<template>
  <div class="container">
    <div class="left-box">
      <n-image width="200px" :src="logo" preview-disabled class="logoclass"></n-image>
      <n-flex vertical>
        <n-card class="left-card">
          <n-image width="500px" :src="background" prewiew-disabled class="backgroundclass"></n-image>
        </n-card>
        <n-gradient-text :size="18" style="color: black;">为用户提供高效快捷的操作体验</n-gradient-text>
      </n-flex>
    </div>
    <div class="right-box">
      <n-switch
      v-model:value="loginStore.active"
      size="medium"
      style="margin-left: 600px; margin-top: -120px;">
        <template #checked>
          🌙
        </template>
        <template #unchecked>
          🌞
        </template>
      </n-switch>
      <n-flex  class="login" vertical style="margin-top: 80px;">
        <h1 class="loginstylesun" v-if="!loginStore.active" size="40">登录</h1>
        <h1 class="loginstyleknight" v-else-if="loginStore.active" size="40">登录</h1>
        <n-form ref="formRef" :model="loginStore.formValue" :rules="loginStore.rules">
          <n-form-item path="username" feedback-style="margin-top:5px;margin-left:185px;">
            <n-input
              v-model:value="loginStore.formValue.username"
              placeholder="手机号"
              clearable
              style="width: 70%; margin-left: 80px;"
              maxlength="11"
              >
              <template #prefix>
              <n-icon :component="User" size="24"/>
              </template>
            </n-input>
          </n-form-item> 
        <n-form-item path="password" feedback-style="margin-top:-10px;margin-left:210px;">
          <n-input
            v-model:value="loginStore.formValue.password"
            placeholder="密码"
            type="password"
            maxlength="16"
            show-password-on="mousedown"
            style="width: 70%; margin-left: 80px; margin-top: -40px;"
            >
            <template #prefix>
            <n-icon :component="Lock" size="24"/>
            </template>
          </n-input>
        </n-form-item>
        <n-flex style="margin-left: 80px; margin-top: 0px">
          <n-switch :rail-style="railStyle" v-model:value="loginStore.remember">
            <template #checked>
              记住我
            </template>
            <template #unchecked>
              忘记我
            </template>
          </n-switch>
          <n-dialog-provider>
            <n-button
          text
          tag="a"
          target="_blank"
          type="primary"
          style="margin-left: 200px;"
          @click="dialogStore.openDialog(UserUpdate)"
        >
          忘记密码
        </n-button>
          </n-dialog-provider>
          
        </n-flex>
        <n-form-item>
            <n-button
          type="info"
          size="medium"
          style="width: 70%; margin-left: 80px; margin-top: 20px;"
          @click="handleValidateClick"
          :disabled="loginStore.loginButtonDisabled"
        >
          登录
        </n-button>
          
        </n-form-item>
        <n-dialog-provider>
          <n-button
          type="warning"
          size="medium"
          style="width: 70%; margin-left: 80px; margin-top: 20px;"
          @click="dialogStore.openDialog(UserRegCode)"
        >
          使用短信验证码登录
        </n-button >
        </n-dialog-provider>
        
      </n-form>
        <n-dialog-provider>
          <n-button
            style="margin-top:20px;"
            text
            tag="a"
            type="info"
            @click="dialogStore.openDialog(UserRegister)"
            >
            还没注册?点击这里
        </n-button>
        </n-dialog-provider>
      </n-flex>
    </div>
  </div>
</template>



<style>
.container {
  display: flex;
  height: 100vh; /* 使容器高度占满整个视口高度 */
  width: 100%;
}

.left-box, .right-box {
  display: flex;
  flex-direction: column;
  justify-content: center; /* 垂直居中 */
  align-items: center; /* 水平居中 */
  padding: 20px;
  box-sizing: border-box; /* 确保内边距不会增加元素的总宽度和高度 */
}

.left-box {
  flex: 1; /* 左边占据一半的空间（或更多，取决于flex属性） */
  background-color: #fffefb;
}

.left-card {
  background-color: #fffefb;
  border: none;
}

.logoclass{
  position: absolute;
  margin-left: -600px;
  margin-top: -650px;
}

.backgroundclass{
  display: flex;
  margin-left: -40px;
  margin-top:-10px;
  width: 500px;
  height: 300px;
}

.right-box {
  flex: 1; /* 右边占据一半的空间 */
  background-color: white; /* 白色背景 */
  border-left: 1px solid #ddd; /* 右边框添加分隔线 */
}


.carousel-image {
  width: 100%;
  height: 100%;
  object-fit: cover; /* 图片保持比例填充容器 */
}

.login{
  width: 500px;
  height: 500px;
  background-color: #d4eaf7;
  border-radius: 10px ;
}

.loginstylesun{
  margin-top: 20px;
  margin-left: 210px;
  color:white;
}

.loginstyleknight{
  margin-top: 20px;
  margin-left: 210px;
  color:black;
}

n-button {
  width: calc(100% - 40px); /* 按钮宽度稍小于容器宽度 */
}


</style>
